package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.*;
import com.itheima.utils.DateUtils;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.Tuple;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/report")
public class ReportController {

    @Reference
    private MemberService memberService;

    @Reference
    private SetmealService setmealService;

    @Reference
    private ReportService reportService;

    @Autowired
    private JedisPool jedisPool;

    @Reference
    private ApiCountService apiCountService;

    @Reference
    private OrderService orderService;

    @Reference
    private GeoMapService geoMapService;

    //会员增长折线图
    @RequestMapping("getMemberReport")
    public Result getMemberReport() {

        //获取日历对象时间就是当前时间
        Calendar calender = Calendar.getInstance();
        //计算过去一年的12个月
        calender.add(Calendar.MONTH, -12);
        //创建新集合
        List<String> list = new ArrayList<>();
        //把现在往前12个月的月份循环存入集合之中
        for (int i = 0; i < 12; i++) {
            //获取当前时间往后推一个月
            calender.add(Calendar.MONTH, 1);
            //将月份格式化yyyy.MM存入集合
            list.add(new SimpleDateFormat("yyyy.MM").format(calender.getTime()));
        }
        //创建Map集合存储时间的list集合
        Map<String, Object> map = new HashMap<>();
        map.put("months", list);

        //根据月份从数据库查询对应的会员数量
        List<Integer> memberCount = memberService.findMemberCountByMonth(list);
        //将查询出来的会员数量集合存入map集合祖红
        map.put("memberCount", memberCount);
        //返回获取会员数量报告成功的result带着map集合
        return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS, map);
    }

    //套餐占比饼状图
    @RequestMapping("/getSetmealReport")
    public Result getSetmealReport() {

        //从数据库查询套餐list集合,包含套餐名和套餐数量
        List<Map<String, Object>> setmealCount = setmealService.findSetmealCount();

        //创建map集合用于存储setmealCount list集合和套餐名称
        Map<String, Object> map = new HashMap<>();
        //map存储setmealCount list集合
        map.put("setmealCount", setmealCount);
        //创建list集合存储套餐名称
        List<String> setmealNames = new ArrayList<>();
        //遍历数据库查询数据
        for (Map<String, Object> m : setmealCount) {
            //获取套餐名称
            String name = (String) m.get("name");
            //将套餐名称存入套餐list集合
            setmealNames.add(name);
        }
        //将套餐名称list集合存入map集合
        map.put("setmealNames", setmealNames);
        //返回获取套餐数量报告成功Result带着map集合
        return new Result(true, MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS, map);
    }

    //会员套餐信息统计表
    @RequestMapping("/getBusinessReportData")
    public Result getBusinessReportData() {
        //try
        try {
            //查询数据库获取信息并存入map集合
            Map<String, Object> result = reportService.getBusinessReport();
            //返回获取数据成功带着map集合
            return new Result(true, MessageConstant.GET_BUSINESS_REPORT_SUCCESS, result);
        } catch (Exception e) {
            e.printStackTrace();
            //返回获取数据失败
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }

    //导出会员套餐数据统计表到Excel表
    @RequestMapping("/exportBusinessReport")
    public Result exportBusinessReport(HttpServletRequest request, HttpServletResponse response) {
        try {
            //远程调用报表服务获取报表数据
            Map<String, Object> result = reportService.getBusinessReport();

            //取出返回结果数据，准备将报表数据写入到Excel文件中
            String reportDate = (String) result.get("reportDate");
            Integer todayNewMember = (Integer) result.get("todayNewMember");
            Integer totalMember = (Integer) result.get("totalMember");
            Integer thisWeekNewMember = (Integer) result.get("thisWeekNewMember");
            Integer thisMonthNewMember = (Integer) result.get("thisMonthNewMember");
            Integer todayOrderNumber = (Integer) result.get("todayOrderNumber");
            Integer thisWeekOrderNumber = (Integer) result.get("thisWeekOrderNumber");
            Integer thisMonthOrderNumber = (Integer) result.get("thisMonthOrderNumber");
            Integer todayVisitsNumber = (Integer) result.get("todayVisitsNumber");
            Integer thisWeekVisitsNumber = (Integer) result.get("thisWeekVisitsNumber");
            Integer thisMonthVisitsNumber = (Integer) result.get("thisMonthVisitsNumber");
            List<Map> hotSetmeal = (List<Map>) result.get("hotSetmeal");
            //获得Excel模板文件绝对路径
            String templateRealPath = request.getSession().getServletContext().getRealPath("template") + File.separator + "report_template.xlsx";

            //读取模板文件创建Excel表格对象
            XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(new File(templateRealPath)));
            XSSFSheet sheet = workbook.getSheetAt(0);
            XSSFRow row = sheet.getRow(2);
            row.getCell(5).setCellValue(reportDate);//日期

            row = sheet.getRow(4);
            row.getCell(5).setCellValue(todayNewMember);//今日新增会员数
            row.getCell(7).setCellValue(totalMember);//总会员数

            row = sheet.getRow(5);
            row.getCell(5).setCellValue(thisWeekNewMember);//本周新增会员数
            row.getCell(7).setCellValue(thisMonthNewMember);//本月新增会员数

            row = sheet.getRow(7);
            row.getCell(5).setCellValue(todayOrderNumber);//今日预约数
            row.getCell(7).setCellValue(todayVisitsNumber);//今日到诊数

            row = sheet.getRow(8);
            row.getCell(5).setCellValue(thisWeekOrderNumber);//本周预约数
            row.getCell(7).setCellValue(thisWeekVisitsNumber);//本周到诊数

            row.getCell(9);
            row.getCell(5).setCellValue(thisMonthOrderNumber);//本月预约数
            row.getCell(7).setCellValue(thisMonthVisitsNumber);//本月到诊数

            int rowNum = 12;
            //热门套餐
            for (Map map : hotSetmeal) {
                String name = (String) map.get("name");
                Long setmeal_count = (Long) map.get("setmeal_count");
                BigDecimal proportion = (BigDecimal) map.get("proportion");
                row = sheet.getRow(rowNum++);
                row.getCell(4).setCellValue(name);//套餐名称
                row.getCell(5).setCellValue(setmeal_count);//预约数量
                row.getCell(6).setCellValue(proportion.doubleValue());//占比
            }

            //通过输出流进行文件下载
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("content-Disposition", "attachment;filename=report.xlsx");
            workbook.write(outputStream);

            outputStream.flush();
            outputStream.close();
            workbook.close();
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL, null);
        }
    }

    //导出会员套餐数据统计表到PDF文件
    @RequestMapping("/exportBusinessReport4PDF")
    public Result exportBusinessReport4PDF(HttpServletRequest request, HttpServletResponse response) {
        try {
            //远程调用报表服务获取报表数据
            Map<String, Object> result = reportService.getBusinessReport();

            //取出返回结果数据，准备将报表数据写入到PDF文件中
            List<Map> hotSetmeal = (List<Map>) result.get("hotSetmeal");
            //获得PDF模板文件绝对路径
            String jrxmlPath = request.getSession().getServletContext().getRealPath("template") + File.separator + "health_business3.jrxml";
            String jasperPath = request.getSession().getServletContext().getRealPath("template") + File.separator + "health_business3.jasper";

            //编译模板
            JasperCompileManager.compileReportToFile(jrxmlPath, jasperPath);
            //填充数据---使用JavaBean数据源方式填充
            JasperPrint jasperPrint = JasperFillManager.fillReport(jasperPath, result, new JRBeanCollectionDataSource(hotSetmeal));

            //通过输出流进行文件下载
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType("application/pdf");
            response.setHeader("content-Disposition", "attachment;filename=report.pdf");

            //输出文件
            JasperExportManager.exportReportToPdfStream(jasperPrint, outputStream);
            outputStream.flush();
            outputStream.close();
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }


    //获取api调用次数(当前时间)
    @RequestMapping("/getApiCountReport")
    public Result getApiCountReport() {
        Jedis jedis = jedisPool.getResource();

        List<List> resultList = new ArrayList<>();
        Set<Tuple> tuples = jedis.zrangeWithScores(RedisConstant.API_COUNT, 0, -1);
        for (Tuple tuple : tuples) {
            //接口调用次数
            int score = (int) Math.floor(tuple.getScore());
            //接口名
            String element = tuple.getElement();
            ArrayList<Object> list = new ArrayList<>();
            list.add(score);
            list.add(element);
            resultList.add(list);
        }
        return new Result(true, "查询成功", resultList);
    }

    //获取api调用次数(按照时间查询)
    @RequestMapping("/getApiCountReportByDate")
    public Result getApiCountReportByDate(@RequestBody List<String> timeList) {
        try {
            long startTime = DateUtils.parseString2Date(timeList.get(0)).getTime();
            long endTime = DateUtils.parseString2Date(timeList.get(1)).getTime();
            List<List> list = apiCountService.findApiCountByDate(startTime, endTime);
            return new Result(true, "查询成功", list);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "查询失败");
        }

    }

    //获取疫情地图信息
    @RequestMapping("/getGeoMapInfo")
    public Result getGeoMapInfo() {
        try {
            List<Map<String, Object>> list = geoMapService.findAll();
            return new Result(true, "查询成功", list);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "查询失败");
        }

    }


    /**
     * 获取会员年龄分布柱状图
     *
     * @return
     */
    @RequestMapping("/getMemberAgeReport")
    public Result getMemberAgeReport() {
        //通过日历对象获取当前年份
        Calendar calendar = Calendar.getInstance();
        //当前年份
        int year = calendar.get(Calendar.YEAR); //2020
        //获取所有会员信息
        List<Member> memberList = memberService.findAll();

        //创建map集合用于保存数据，发送到前台页面
        Map<String, Object> map = new HashMap<>();
        //添加年龄段数据
        List<String> ageGroup = new ArrayList<>();
        ageGroup.add("婴幼儿");
        ageGroup.add("少儿");
        ageGroup.add("青少年");
        ageGroup.add("少年");
        ageGroup.add("中年");
        ageGroup.add("老年");
        map.put("ageGroup", ageGroup);

        //统计每个年龄段的数量
        int count1 = 0;
        int count2 = 0;
        int count3 = 0;
        int count4 = 0;
        int count5 = 0;
        int count6 = 0;

        for (Member member : memberList) {
            //获取每个会员的生日
            Date birthday = member.getBirthday();
            //判断生日是否为空
            if (birthday != null) {
                Calendar c = Calendar.getInstance();
                c.setTime(birthday);
                //获取每个会员的出生年份
                int memberYear = c.get(Calendar.YEAR);
                //System.out.println(memberYear);
                //计算生日
                int age = year - memberYear;
                if (age >= 0 && age <= 6) {
                    count1++;
                } else if (age >= 7 && age <= 12) {
                    count2++;
                } else if (age >= 13 && age <= 17) {
                    count3++;
                } else if (age >= 18 && age <= 45) {
                    count4++;
                } else if (age >= 46 && age <= 69) {
                    count5++;
                } else if (age >= 70) {
                    count6++;
                }
            }
        }
        //添加年龄段统计
        List<Integer> memberCount = new ArrayList<>();
        memberCount.add(count1);
        memberCount.add(count2);
        memberCount.add(count3);
        memberCount.add(count4);
        memberCount.add(count5);
        memberCount.add(count6);
        map.put("memberCount", memberCount);
        return new Result(true, MessageConstant.GET_MEMBER_AGRGROUP_REPORT_SUCCESS, map);
    }

    /**
     * 统计套餐收入
     *
     * @return
     */
    @RequestMapping("/getIncomeReport")
    public Result getIncomeReport(@RequestBody Map map) {
        System.out.println(map);
        //定义map集合
        Map<String, Object> data = new HashMap<>();
        //根据时间范围获取套餐名和套餐收入
        //从数据库查询套餐list集合,包含套餐名和套餐收入
        List<Map<String, Object>> incomeCount = setmealService.findIncomeCount(map);

        //计算总收入
        Map<String, Object> totalRevenue = new HashMap<>();
        int zsr = 0;
        totalRevenue.put("name", "总收入");
        for (Map<String, Object> stringObjectMap : incomeCount) {
            //int shouru = Integer.parseInt((String) stringObjectMap.get("value"));
            Double shouru = (Double) stringObjectMap.get("value");
            zsr += shouru;
        }
        totalRevenue.put("value", zsr);
        //将总数据的map集合假如到集合中
        incomeCount.add(totalRevenue);

        data.put("incomeCount", incomeCount);

        List<String> names = new ArrayList<>();
        if (incomeCount != null && incomeCount.size() > 0) {
            for (Map<String, Object> row : incomeCount) {
                //获取套餐名称
                String setmealName = (String) row.get("name");
                names.add(setmealName);
            }
        }
        data.put("setmealName", names);
        return new Result(true, MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS, data);
    }

    /**
     * 统计每日预约数，到诊数
     *
     * @return
     */
    @RequestMapping("/getVisitCount")
    public Result getVisitCount(@RequestBody Map map) throws Exception {
        //检测
        System.out.println(map);
        Map<String, Object> mapList = orderService.findAandVCount(map);
        return new Result(true, MessageConstant.GET_A_S_COUNT_SUCCESS, mapList);
    }
}
